<template>
  <div class="register-page">
    <el-form :model="registerForm" class="registerForm" status-icon :rules="rules" ref="registerForm">
      <h2 class="title">欢迎你的加入</h2>
      <el-form-item prop="username">
        <el-input v-model="registerForm.username" placeholder="给自己起一个名字吧">
          <i slot="prefix" class="ali-icon el-ali-yonghu"></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="registerForm.password" placeholder="保护好自己的密码呦">
          <i slot="prefix" class="ali-icon el-ali-mima"></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="password2">
        <el-input type="password" v-model="registerForm.password2" placeholder="麻烦再写一次">
          <i slot="prefix" class="ali-icon el-ali-mima"></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="mobile">
        <el-input v-model="registerForm.mobile" placeholder="靓仔，请填写手机号">
          <i slot="prefix" class="ali-icon el-ali-shouji"></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="verifyCode">
        <el-row>
          <el-col :span="12">
            <el-input v-model="registerForm.verifyCode">
              <i slot="prefix" class="ali-icon el-ali-yanzhengma"></i>
            </el-input>
          </el-col>
          <el-col :span="10" :offset="2">
            <el-button style="width:100%" type="primary" round @click="getCheckCode" :disabled="btnDisabled">{{content}}</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button style="width:100%" type="primary" @click="register">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getMobileCheckCode } from '@/api/verification'
import { register } from '@/api/user'

export default {
  data() {
    var validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'));
      }
      callback();
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.registerForm.password2 !== '') {
          this.$refs.registerForm.validateField('password2');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入电话号码'));
      } else if (!this.isvalidPhone(value)) {
        callback(new Error('请输入正确的 11 位手机号码'));
      } else {
        callback();
      }
    };
    var validateverifyCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'));
      } else if (!this.isvalidverifyCode(value)) {
        callback(new Error('请输入正确的验证码'));
      } else {
        callback();
      }
    };
    return {
      content: "获取验证码",
      btnDisabled: false,
      registerForm: {
        username: "",
        password: "",
        password2: "",
        mobile: "",
        verifyCode: ""
      },
      rules: {
        username: [
          { validator: validateUsername, trigger: 'change' },
          { max: 10, message: '长度不能超过 10 个字符哦', trigger: 'change' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' },
          { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
        ],
        password2: [
          { validator: validatePass2, trigger: 'blur' },
          { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
        ],
        mobile: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        verifyCode: [
          { validator: validateverifyCode, trigger: 'blur', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    register() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          register(this.registerForm.verifyCode, {
            username: this.registerForm.username,
            password: this.registerForm.password,
            mobile: this.registerForm.mobile
          }).then(res => {
            if (res.flag) {
              this.$message.success("注册成功")
              this.$router.push("/login")
            } else if (res.code == 20008) {
              this.$message.warning("用户名重复")
            } else if (res.code == 20011) {
              this.$message.warning("验证码错误")
            }
          })
        } else {
          return false;
        }
      });
    },
    isvalidPhone(str) {
      const reg = /^1[3-9]\d{9}$/
      return reg.test(str)
    },
    isvalidverifyCode(str) {
      if (str.length != 6) {
        return false;
      }
      var numReg = /^[0-9]+$/
      return numReg.test(str)
    },
    getCheckCode() {
      if (!this.registerForm.mobile || !this.isvalidPhone(this.registerForm.mobile)) return
      getMobileCheckCode({ mobile: this.registerForm.mobile }).then(res => {
        if (res.flag) {
          this.$message.success("短信已发送");
          this.countdown()
        } else if (res.code == 20010) {
          this.$message.warning("手机号已存在");
        } else if (res.code == 20014) {
          this.$message.warning("请求次数过多，请稍后再试");
        }
      })
    },
    countdown() {
      // 控制倒计时及按钮是否可以点击
      const TIME_COUNT = 60
      this.count = TIME_COUNT
      this.timer = window.setInterval(() => {
        if (this.count > 0 && this.count <= TIME_COUNT) {
          // 倒计时时不可点击
          this.btnDisabled = true
          // 计时秒数
          this.count--
          // 更新按钮的文字内容
          this.content = this.count + 's后重新获取'
        } else {
          // 倒计时完，可点击
          this.btnDisabled = false
          // 更新按钮文字内容
          this.content = '获取短信验证码'
          // 清空定时器!!!
          clearInterval(this.timer)
          this.timer = null
        }
      }, 1000)
    }
  }
}
</script>

<style scoped>
.title {
  text-align: center;
  font-size: 22px;
  color: black;
  font-weight: bold;
  margin: 20px 0;
}
.register-page {
  height: 100%;
  width: 100%;
  background: #f0f2f5;
  background-image: url("https://img.lesslesson.com/register-page-bg.svg");
  background-repeat: no-repeat;
  background-position: center 110px;
  background-size: 100%;
  position: fixed;
  left: 0;
  top: 0;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
@media screen and (max-width: 700px) {
  .registerForm {
    width: 70%;
  }
}
@media screen and (min-width: 700px) and (max-width: 1000px) {
  .registerForm {
    width: 50%;
  }
}
@media screen and (min-width: 1000px) and (max-width: 1200px) {
  .registerForm {
    width: 30%;
  }
}
@media screen and (min-width: 1200px) {
  .registerForm {
    width: 25%;
  }
}
.ali-icon {
  margin-left: 3px;
}
</style>


